package com.ys.controller.api.finance;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.entity.business.TpAmazonSeller;
import com.ys.entity.business.TpAmazonShop;
import com.ys.entity.finance.TcwFinancesEventGroupsOp;
import com.ys.entity.sys.YsCol;
import com.ys.enume.AmazonSellerEnum;
import com.ys.enume.sys.YsColEnum;
import com.ys.service.finance.TcwFinancesEventGroupsOpService;
import com.ys.service.log.ApiLogService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.RedisUtil;
import com.ys.util.dhecp.DateUtils;
import com.ys.vo.ApiResponse;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/tcwFinancesEventGroupsOp")
public class ApiInterTcwFinancesEventGroupsOpController {

	public static Long MENU_ID = 10203L;
	private static org.slf4j.Logger logger = LoggerFactory.getLogger(ApiInterTcwFinancesEventGroupsOpController.class);

	private Object lock = new Object();


	@Autowired
	private CommonApiService<TcwFinancesEventGroupsOp> commonApiService;

	@Autowired
	private ApiLogService apiLogService;

	@Autowired
	private RedisUtil redisUtil;

	@Autowired
	private TcwFinancesEventGroupsOpService tcwFinancesEventGroupsOpService;


	@RequiresPermissions("tcwFinancesEventGroupsOp:view")
	@RequestMapping("/search")
    @ResponseBody
	public LayuiTableVoJA search(@ModelAttribute TcwFinancesEventGroupsOp cond,String conditions){
		cond.setOrderby("A.createTime DESC");
		return commonApiService.searchLay(cond);
	}

	@RequestMapping("/export")
	@ResponseBody
	public R export(@ModelAttribute TcwFinancesEventGroupsOp cond, String conditions) throws Exception{

		cond.setPage(0).setSize(999999);
		cond.setOrderby("A.createTime DESC");
		List<Map<String, Object>> listData = cond
				.queryMap();

		List<YsCol> listField = new YsCol()
				.setMenuId(MENU_ID)
				.setFrontShow(YsColEnum.FrontShow.SHOW.value)
				.setOrderby("A.SortNo asc")
				.queryList();


		ExportExcelUtils<TcwFinancesEventGroupsOp> util = new ExportExcelUtils<TcwFinancesEventGroupsOp>(new TcwFinancesEventGroupsOp());

		String toFilePath = util.exportExcel(listData, listField, "财务事件表");
		UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
		return R.ok(dto.getUrl());
	}



	/**
	 * 重新刷新
	 * @throws Exception
	 */
	@RequiresPermissions("tcwFinancesEventGroupsOp:view")
	@PostMapping("/refresh")
	@ResponseBody
	public R refresh(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData) {
//		synchronized (lock) {
			try {
				Map<Object, Object> redisMap = redisUtil.hGetAll("THREAD_APIOP");
				for (Map.Entry<Object, Object> e : redisMap.entrySet()) {
					if (e.getValue().equals("1")) {
						return R.error("正在执行重新刷新,请稍等后再操作!");
					}
				}

				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String currentDate = sdf.format(new Date());

				String startDate = params.get("startDate").toString();
				String endDate = params.get("endDate").toString();
				if (currentDate.equals(endDate)) {
					return R.error("时间不允许为当天,核实后再操作!");
				}

				// 将字符串转换为LocalDate对象
				LocalDate date1 = LocalDate.parse(startDate);
				LocalDate date2 = LocalDate.parse(endDate);

				// 计算两个日期之间的天数
				long daysBetween = ChronoUnit.DAYS.between(date1, date2);

				if (daysBetween > 180){
					return R.error("时间范围不允许超过180天,核实后再操作!");
				}
				if (daysBetween < 0){
					return R.error("开始时间必须大于结束时间,核实后再操作!");
				}

				JSONArray detailJA = JSON.parseArray(subData);
				if (detailJA == null || detailJA.size() == 0) {
					return R.error("公司列表不能为空");
				}

				//转换时间
				Date sDate = sdf.parse(startDate);
				Date eDate = sdf.parse(endDate);

				Calendar calendar = Calendar.getInstance();
				calendar.setTime(sDate);
				calendar.set(Calendar.HOUR_OF_DAY,00);
				calendar.set(Calendar.MINUTE,00);
				calendar.set(Calendar.SECOND,00);

				Calendar calendar1 = Calendar.getInstance();
				calendar1.setTime(eDate);
				calendar1.set(Calendar.HOUR_OF_DAY,23);
				calendar1.set(Calendar.MINUTE,59);
				calendar1.set(Calendar.SECOND,59);

				Date startTime = calendar.getTime();
				String startTimeStr = DateUtils.convertDateToTDate(startTime);
				Date endTime = calendar1.getTime();
				String endTimeStr = DateUtils.convertDateToTDate(endTime);

				StringBuilder rs = new StringBuilder();
				// 拼接id
				for (int i = 0; i < detailJA.size(); i++) {
					JSONObject detailJO = detailJA.getJSONObject(i);
					rs.append("," + Integer.valueOf(detailJO.get("id").toString()));
				}
				List<Map<String, Object>> tpAmazonSellerList = new TpAmazonSeller()
						.addLeftJoin("TP_AmazonRegion tar on tar.Code = A.regionCode")//平台地区
						.addLeftJoin("TP_AmazonShop B on B.sellerId = A.sellerId")//店铺
						.addField("tar.AwsRegion awsRegion,tar.AmazonServiceUrl amazonServiceUrl,tar.code amazonRegionCode")
						.where("A.authorizeState = '已授权' AND B.Id IN (" + rs.substring(1,rs.length()) + ")")
						.setStatus(1)
						.queryMap();
				JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(tpAmazonSellerList));
				for (int i = 0; i < 20; i++) {
					redisUtil.hPut("THREAD_APIOP", String.valueOf(i), "0");
				}

				for (int i = 0; i < jsonArray.size(); i++) {
					JSONObject jsonObject = jsonArray.getJSONObject(i);
						boolean variable = true;
						while (variable) {
							redisMap = redisUtil.hGetAll("THREAD_APIOP");
							for (Map.Entry<Object, Object> e : redisMap.entrySet()) {
								if (e.getValue().equals("1")) {
									continue;
								} else if (e.getValue().equals("0")) {
									redisUtil.hPut("THREAD_APIOP", String.valueOf(e.getKey()), "1");
//								 开启线程
									Thread t = new Thread(() -> {
										ApiResponse apiResponse = null;
										try {
//											apiResponse = tcwFinancesEventGroupsOpService.getGroupsOp(jsonObject, startTimeStr, endTimeStr);
										} catch (Exception exception) {
											exception.printStackTrace();
											redisUtil.hPut("THREAD_APIOP", String.valueOf(e.getKey()), "0");
										}
										if (apiResponse.getCode() == 500) {
											apiLogService.addApiLog("Amazon", "GetGroupsOpMr", "ECP_API定时获取亚马逊财务事件信息出错，条件queryParams：" + JSON.toJSONString(jsonObject), "店铺:" + jsonObject.get("sellerName").toString(), apiResponse.getCode(), apiResponse.getMessage());
										}
										logger.info("***********手动刷新财务目录GetGroupsOpMr，结束***********");
										redisUtil.hPut("THREAD_APIOP", String.valueOf(e.getKey()), "0");
									});
									t.start();
//									Thread.sleep(500L);
								}
								variable = false;
								break;
							}
						}
					}
			}catch (Exception e){
				return R.error("刷新失败!");
			}
		return R.ok("刷新成功");
	}


}
